"use strict";

const path = require("path");
const Package = require("@hcnhistudy/package");
const log = require('@hcnhistudy/log')
const { spawn } = require('@hcnhistudy/utils')
const SETTINGS = {
  init: "@hcnhistudy/init",
};

const CACHE_DIR = "dependencies";

async function exec(projectName, option, parentoOtion) {
  // console.log(parentoOtion.name());// 命令名称
  // console.log(projectName); // 命令的值
  // console.log(option);// 当前命令
  const packageName = SETTINGS[parentoOtion.name()];
  const packageVersion = "latest";
  let targetPath = process.env.CLI_TARGET_PATH;
  const homePath = process.env.CLI_HOME_PATH;
  let storeDir = ""; // 缓存模块目录
  let pkg;
  if (targetPath) {
    pkg = new Package({
      targetPath,
      homePath,
      packageName,
      packageVersion,
    });
  } else {
    targetPath = path.resolve(homePath, CACHE_DIR); // C:\Users\Administrator\.hcnhistudy-cli\dependencies
    storeDir = path.resolve(targetPath, "node_modules"); // C:\Users\Administrator\.hcnhistudy-cli\dependencies\node_modules
    pkg = new Package({
      targetPath,
      homePath,
      packageName,
      packageVersion,
      storeDir,
    });
    // 检查当前package是否存在

    if (await pkg.exists()) {
      await pkg.update();
    } else {
      await pkg.install();
    }
  }

  const rootFile = pkg.getRootFilePath();
  if (rootFile) {
    // node子进程开发
    try {
      let args = Array.from(arguments);
      const cmd = args[args.length - 1];
      const o = Object.create(null);
      Object.keys(cmd).forEach((key) => {
        if (
          cmd.hasOwnProperty(key) && // 自身属性
          !key.startsWith("_") && // 不是 _ 开始
          key !== "parent"
        ) {
          o[key] = cmd[key];
        }
      });
      args[args.length - 1] = o;
      // console.log(args, 'args')
      const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`;
      const option = {
        cwd: process.cwd(),
        stdio: "inherit",
      };
      let child = spawn("node", ["-e", code], option);
      child.on("error", (e) => {
        log.error(e.message);
        process.exit(1); // 发生错误，中断执行
      });
      child.on("exit", (e) => {
        log.verbose("命令执行成功：" + e.message);
        process.exit(e);
      });
      // console.log(process.cwd()); // 当前执行得目录
    } catch (e) {
      log.error(e.message);
    } // require(rootFile).apply(null, arguments)
    // console.log(args, 'kkkkkkkkk');
  }
}

module.exports = exec;
